package crawler

import (
	"log"
	"net/http"
	"strings"

	"github.com/PuerkitoBio/goquery"
	"golang.org/x/text/encoding/simplifiedchinese"
)

// Dy2018ComCrawler 电影抓取程序
type Dy2018ComCrawler struct {
}

// GetCrawlerURL 返回爬虫目标地址
func (c *Dy2018ComCrawler) GetCrawlerURL() string {
	const url string = "https://www.dy2018.com/"
	return url
}

// StartCrawler 开始抓取新闻
func (c *Dy2018ComCrawler) StartCrawler() ([]map[string]string, error) {

	url := c.GetCrawlerURL()
	res, err := http.Get(url)

	if err != nil {
		log.Println(err)
		return nil, err
	}
	defer res.Body.Close()

	if res.StatusCode != 200 {
		log.Printf("status code error: %d %s", res.StatusCode, res.Status)
	}

	// Load the HTML document
	reader := simplifiedchinese.GB18030.NewDecoder().Reader(res.Body)
	doc, err := goquery.NewDocumentFromReader(reader)
	if err != nil {
		log.Fatal(err)
	}

	filmMaps := []map[string]string{}

	// Find the review items
	doc.Find(".co_content222").Each(func(i int, cont *goquery.Selection) {
		// For each item found, get the band and title
		cont.Find("li").Each(func(i int, s *goquery.Selection) {
			elementA := s.Find("a")

			title := elementA.Text()
			href, _ := elementA.Attr("href")

			if !strings.Contains(title, "播放器") {
				one := map[string]string{}
				one["title"] = title
				one["url"] = url + href
				filmMaps = append(filmMaps, one)
			}

		})
	})
	if err != nil {
		return nil, err
	}

	return filmMaps, nil
}

// CrawlerMagnet 爬取页面下的磁力链接
func (c *Dy2018ComCrawler) CrawlerMagnet(url string) (interface{}, error) {

	res, err := http.Get(url)

	if err != nil {
		log.Println(err)
		return nil, err
	}
	defer res.Body.Close()

	if res.StatusCode != 200 {
		log.Printf("status code error: %d %s", res.StatusCode, res.Status)
	}

	// Load the HTML document
	reader := simplifiedchinese.GB18030.NewDecoder().Reader(res.Body)
	doc, err := goquery.NewDocumentFromReader(reader)
	if err != nil {
		log.Fatal(err)
	}

	magnet := ""

	// 只查第一个标签
	doc.Find("#downlist table").EachWithBreak(func(i int, s *goquery.Selection) bool {
		elementA := s.Find("a")
		magnet = elementA.Text()
		return false
	})

	return magnet, nil
}
